package watcher

import (
	"playbook/ginsvr/src/global"
	"playbook/ginsvr/src/orm"
	"playbook/ginsvr/src/utils/fileutil"
	"playbook/ginsvr/src/utils/httputil"

	"github.com/fsnotify/fsnotify"
	"github.com/sirupsen/logrus"
)

var Watcher *fsnotify.Watcher
var WatchMap map[string]string
var err error

func init() {
	WatchMap = make(map[string]string)
	Watcher, err = fsnotify.NewWatcher()
	if err != nil {
		global.LOG.WithFields(logrus.Fields{
			"err": err,
		}).Error("init watcher err.")
	}

	//done := make(chan bool)
	go func() {
		for {
			select {
			case e, ok := <-Watcher.Events:
				if !ok {
					global.LOG.Info("监听到文件失败", e.Name)
					continue
				}
				global.LOG.Info("监听到文件变化", e.Name)
				switch e.Op {
				case fsnotify.Create:
					sendFileWriteMsg(e.Name)
				case fsnotify.Write:
					sendFileWriteMsg(e.Name)
				case fsnotify.Remove:
					sendFileDelMsg(e.Name)
				case fsnotify.Rename:
					sendFileWriteMsg(e.Name)
				case fsnotify.Chmod:
					global.LOG.Info("属性修改事件", e.Op)
				default:
					global.LOG.Info("some thing else")
				}
			case err, ok := <-Watcher.Errors:
				if !ok {
					global.LOG.Info("error:", err)
				}
			}
		}
	}()
	//<-done
}

func sendFileDelMsg(filename string) {
	ip := getWatchIP(filename)
	if ip != "" {
		httputil.FileDel(ip, fileutil.GetRelaPath(filename))
	}
}

func sendFileWriteMsg(filename string) {
	flst := fileutil.ReadSrcFile(filename, true)
	ip := getWatchIP(filename)
	if ip != "" {
		httputil.FileReWrite(ip, fileutil.GetRelaPath(filename), flst)
	}
}

func AddWatchFile(srcpath string, ip string) {
	localpath := orm.GetLocalPath(global.USER)
	path := localpath.LocalPath + global.PTHSEP + srcpath

	if _, ok := WatchMap[fileutil.SepTransform(srcpath)]; !ok {
		global.LOG.Info("watch add", path)
		Watcher.Add(fileutil.SepTransform(path))
	}
	WatchMap[fileutil.SepTransform(srcpath)] = ip
}

func getWatchIP(filename string) string {
	srcpath := fileutil.GetRelaPath(filename)
	ip, ok := WatchMap[fileutil.SepTransform(srcpath)]

	if !ok {
		return ""
	}
	return ip
}
